package com.pig4cloud.pig.ads.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.ads.pig.mapper.AdPicturePlatformMapper;
import com.pig4cloud.pig.ads.pig.mapper.AdPlanMapper;
import com.pig4cloud.pig.ads.service.AdPlanTempService;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.ads.service.TtAdCreativeTempService;
import com.pig4cloud.pig.api.dto.AdPlanTempDto;
import com.pig4cloud.pig.api.entity.AdPlan;
import com.pig4cloud.pig.api.enums.InventoryCatalogEnum;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.api.entity.AdPlanTemp;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.api.entity.TtAdCreativeTemp;
import com.pig4cloud.pig.ads.pig.mapper.TtAdCreativeTempMapper;
import com.pig4cloud.pig.common.core.util.R;

import lombok.RequiredArgsConstructor;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class TtAdCreativeTempServiceImpl extends ServiceImpl<TtAdCreativeTempMapper, TtAdCreativeTemp> implements TtAdCreativeTempService {
	private final Logger logger = LoggerFactory.getLogger(TtAdCreativeTempServiceImpl.class);

	private final TtAdCreativeTempMapper ttAdCreativeTempMapper;

	private final AdvService advService;

	private final AdPlanMapper adPlanMapper;

	private final AdPlanTempService adPlanTempService;
	@Resource
	private AdPicturePlatformMapper adPicturePlatformMapper;

	@Override
	public R create(TtAdCreativeTemp record) {
		logger.info("{}创意的请求参数为：{}",StringUtils.isBlank(record.getCreativeMaterialMode())?"自定义":"程序化",record.getCreatives());
		//数据校验
		R validateResult = this.dataValidate(record);
		if (validateResult.getCode() != CommonConstants.SUCCESS) {return validateResult;}
		record.setPlatformId(Short.valueOf("1"));
		//同步状态，默认 未同步
		record.setSyncStatus(Short.valueOf("0"));
		record.setCreatetime(new Date());
		Integer userId = SecurityUtils.getUser().getId();
		record.setCreatorId(userId);
		int i;
		if (Objects.nonNull(record.getId())) {
			i = ttAdCreativeTempMapper.updateById(record);
		} else {
			TtAdCreativeTemp req = new TtAdCreativeTemp();
			req.setAdId(record.getAdId());
			TtAdCreativeTemp queryTemp = baseMapper.selectOne(Wrappers.<TtAdCreativeTemp>query().lambda()
					.eq(TtAdCreativeTemp::getAdId,record.getAdId())
					.eq(TtAdCreativeTemp::getCreatorId,userId)
					.eq(TtAdCreativeTemp::getAdvertiserId,record.getAdvertiserId())
					.orderByDesc(TtAdCreativeTemp::getId).last("limit 1 "));
			if (Objects.nonNull(queryTemp)) {
				record.setId(queryTemp.getId());
				i = ttAdCreativeTempMapper.updateById(record);
			} else {
				i = ttAdCreativeTempMapper.insert(record);
			}
		}
		// 新版计划中新增广告位信息（旧版计划中在创意维度） 页面位置还在创意，接口兼容-减少前端开发工作量
		// 更新广告临时表的的广告位信息
		//先查询更新吧
		AdPlanTemp updateDto = adPlanTempService.getById(record.getAdId());
		updateDto.setInventoryCatalog(record.getInventoryCatalog());
		if (InventoryCatalogEnum.SMART.getValue().equals(record.getInventoryCatalog())){
			updateDto.setSmartInventory(InventoryCatalogEnum.SMART.getValue());
		} else if (InventoryCatalogEnum.UNIVERSAL.getValue().equals(record.getInventoryCatalog())) {
			updateDto.setSmartInventory(InventoryCatalogEnum.UNIVERSAL.getValue());
		} else if (InventoryCatalogEnum.UNIVERSAL_SMART.getValue().equals(record.getInventoryCatalog())) {
			updateDto.setSmartInventory("UNIVERSAL_ALL");
		} else if (InventoryCatalogEnum.MANUAL.getValue().equals(record.getInventoryCatalog())) {
			//首选媒体
			updateDto.setInventoryType(record.getInventoryType());
		} else if (InventoryCatalogEnum.SCENE.getValue().equals(record.getInventoryCatalog())) {
			//场景广告位
			updateDto.setSceneInventory(record.getSceneInventory());
		}
		adPlanTempService.updateById(updateDto);
		if (SqlHelper.retBool(i)) {
			return R.ok(record, "操作成功");
		} else {
			return R.failed("操作失败");
		}
	}

	@Override
	public TtAdCreativeTemp detail(Integer id) {
		return ttAdCreativeTempMapper.selectById(id);
	}

	@Override
	public R update(TtAdCreativeTemp record) {
		if (SqlHelper.retBool(ttAdCreativeTempMapper.updateById(record))) {
			return R.ok(record, "添加成功");
		} else {
			return R.failed("添加失败");
		}
	}

	@Override
	public R delete(Long id) {
		if (SqlHelper.retBool(ttAdCreativeTempMapper.deleteById(id))) {
			return R.ok("添加成功");
		} else {
			return R.failed("添加失败");
		}
	}

	@Override
	public R latestRecord(Long advertiserId, Long adId, Long id) {
		TtAdCreativeTemp req = new TtAdCreativeTemp();
		TtAdCreativeTemp record = null;
		if (Objects.nonNull(id)) {
			record = ttAdCreativeTempMapper.selectById(id);
			if (Objects.isNull(record)) {
				return R.failed("广告创意临时表中无此广告创意");
			}
			//兼容前端少修改交互，获取广告位置信息
			this.setAdPosition(record);
			return R.ok(record);
		}
		PigUser usr = SecurityUtils.getUser();
		if (usr == null) {
			return R.failed("未获取到用户id");
		}
		Integer uid = usr.getId();
		if (null == advertiserId) {
			return R.failed("未输入广告账户id");
		}
//		if (null == adId) {
//			return R.failed("未输入广告计划id");
//		}
		record=baseMapper.selectOne(Wrappers.<TtAdCreativeTemp>query().lambda().eq(adId != null, TtAdCreativeTemp::getAdId,adId).eq(TtAdCreativeTemp::getCreatorId,uid).eq(TtAdCreativeTemp::getAdvertiserId,advertiserId).last("order by id desc limit 1 "));
		if (Objects.nonNull(record)) {
			//兼容前端少修改交互，获取广告位置信息
			this.setAdPosition(record);
			return R.ok(record);
		}
		return R.ok(null);
	}

	private void setAdPosition(TtAdCreativeTemp record){
		AdPlanTemp adPlan = adPlanTempService.getById(record.getAdId());
		if (adPlan != null) {
			record.setInventoryType(null);
			record.setSceneInventory(null);
			record.setInventoryCatalog(adPlan.getInventoryCatalog());
			if (InventoryCatalogEnum.SMART.getValue().equals(adPlan.getInventoryCatalog())){
				record.setSmartInventory(new Byte("1"));
			} else if (InventoryCatalogEnum.UNIVERSAL.getValue().equals(record.getInventoryCatalog())
				|| InventoryCatalogEnum.UNIVERSAL_SMART.getValue().equals(record.getInventoryCatalog())) {
				record.setSmartInventory(new Byte("2"));
			} else if (InventoryCatalogEnum.MANUAL.getValue().equals(record.getInventoryCatalog())) {
				record.setInventoryType(adPlan.getInventoryType());
			} else if (InventoryCatalogEnum.SCENE.getValue().equals(record.getInventoryCatalog())) {
				record.setSceneInventory(adPlan.getSceneInventory());
			}
		}
	}

	private R dataValidate(TtAdCreativeTemp record) {
		if (record.getAdId() == null) {
			return R.failed("缺少 广告计划id");
		}

		if (record.getAdvertiserId() == null) {
			return R.failed("缺少广告账户id");
		}

		if (record.getThirdIndustryId() == null) {
			return R.failed("缺少创意分类");
		}

		// 20220321 头条接口调整为非必填
//		if (StringUtils.isBlank(record.getAdKeywords())) {
//			return R.failed("缺少创意标签");
//		}

		if (StringUtils.isBlank(record.getCreatives())) {
			return R.failed("未提供 创意内容");
		}

		if (StringUtils.isNotBlank(record.getAdKeywords())) {
			String[] arr1 = record.getAdKeywords().split(",");
			if (arr1.length > 20) {
				return R.failed("最多20个创意标签");
			}
			for (String item : arr1) {
				if (item.length() > 10) {
					return R.failed("每个标签长度不超过10个字符");
				}
			}
		}

		AdPlanTemp adPlan = adPlanTempService.selectAdPlanTempById(record.getAdId());
		//投放范围
		String deliveryRange = adPlan.getDeliveryRange();
		//投放范围为穿山甲时 广告位大类 默认为首选媒体
		if ("UNION".equals(deliveryRange)) {
			//穿山甲 没有卡片信息 暂时先不解析json校验 component_materials
			record.setInventoryCatalog(InventoryCatalogEnum.MANUAL.getValue());
			//媒体只能为穿山甲
			record.setInventoryType("INVENTORY_UNION_SLOT");
		}
		if (StringUtils.isBlank(record.getInventoryCatalog())) {
			return R.failed("广告位置不能为空");
		}
		if (InventoryCatalogEnum.MANUAL.getValue().equals(record.getInventoryCatalog())
				&& StringUtils.isBlank(record.getInventoryType())) {
			return R.failed("投放位置（首选媒体）不能为空");
		}
		if (InventoryCatalogEnum.SCENE.getValue().equals(record.getInventoryCatalog())
				&& StringUtils.isBlank(record.getSceneInventory())) {
			return R.failed("投放位置（场景）不能为空");
		}

		//2.4.2新营销链路 TitleList、ImageList()存储在creatives字段中
		//获取创意的素材类型
		List<String> imagesMode = this.getImagesMode(record);
		if (CollectionUtils.isEmpty(imagesMode)) {
			return R.failed("创意内容不能为空");
		}

		//默认-投放范围
		if ("DEFAULT".equals(deliveryRange)) {
			//按媒体指定位置（抖音）  只支持  竖版视频、横版视频
			if (StringUtils.isNotBlank(record.getInventoryType())
					&& record.getInventoryType().contains("INVENTORY_AWEME_FEED")) {
				if (!imagesMode.contains("CREATIVE_IMAGE_MODE_VIDEO")
						&& !imagesMode.contains("CREATIVE_IMAGE_MODE_VIDEO_VERTICAL")) {
					return R.failed("抖音必须提供视频素材，请添加视频素材");
				}
			}
			//按场景指定位置（视频后贴和尾帧场景）     不支持 竖版视频
			if (StringUtils.isNotBlank(record.getSceneInventory())
					&& record.getSceneInventory().equals("TAIL_SCENE")) {
				for (String mode : imagesMode) {
					if (mode.equals("CREATIVE_IMAGE_MODE_VIDEO_VERTICAL")){
						return R.failed("广告位置为视频后贴和尾帧场景时,不支持竖版视频");
					}
				}
			}
			//首选媒体
			if (InventoryCatalogEnum.MANUAL.getValue().equals(record.getInventoryCatalog())) {
				//媒体类型包含抖音,创意组件必填
				JSONArray componentIds = this.getComponentMaterials(record);
				if (record.getInventoryType().contains("INVENTORY_AWEME_FEED")) {
					if (componentIds == null && componentIds.size()<=0) {
						return R.failed("媒体包含抖音时基础创意组件必填");
					}
				} else {
					if (componentIds != null && componentIds.size()>0) {
						return R.failed("使用创意组件时必须包含抖音信息流");
					}
				}

			}

		} else if ("UNION".equals(deliveryRange)) {
			if (record.getSmartInventory() != null) {
				return R.failed("广告计划选择穿山甲时,广告位置不能为优选广告位");
			}
			if (StringUtils.isNotBlank(record.getSceneInventory())) {
				return R.failed("广告计划选择穿山甲时,创意不能按场景指定位置");
			}
			if (StringUtils.isNotBlank(record.getInventoryType()) &&
					!record.getInventoryType().equals("INVENTORY_UNION_SLOT")) {
				return R.failed("广告计划选择穿山甲时,创意的广告位置只能为穿山甲");
			}
			if (record.getIsCommentDisable() != null) {
				return R.failed("广告计划选择穿山甲时,不能设置 广告评论开关");
			}
			//投放形式=原生，支持所有素材类型
			//投放形式=开屏，仅支持 开屏图片
			if (adPlan.getUnionVideoType().equals("SPLASH_VIDEO")) {
				for (String mode : imagesMode) {
					if (!mode.equals("CREATIVE_IMAGE_MODE_UNION_SPLASH")) {
						//CREATIVE_IMAGE_MODE_UNION_SPLASH        穿山甲开屏图片
						//CREATIVE_IMAGE_MODE_UNION_SPLASH_VIDEO  穿山甲开屏视频
						return R.failed("穿山甲开屏广告计划只支持 开屏 类素材");
					}
				}
			}

			//投放形式=激励视频，仅支持 竖版视频、横版视频
			if (adPlan.getUnionVideoType().equals("REWARDED_VIDEO")) {
				for (String mode : imagesMode) {
					if (!mode.equals("CREATIVE_IMAGE_MODE_VIDEO")
							&& !mode.equals("CREATIVE_IMAGE_MODE_VIDEO_VERTICAL")) {
						return R.failed("穿山甲-激励视频广告计划只支持视频素材");
					}
				}
			}

			//穿山甲必须 提供行动号召 v2.4.2新营销链路不需要ActionText，暂时保留
			if (StringUtils.isBlank(record.getActionText())) {
				return R.failed("广告计划为穿山甲，未创意指定 行动号召");
			}

			//媒体为穿山甲时不需要基础创意组件
			JSONArray componentIds = this.getComponentMaterials(record);
			if (componentIds != null && componentIds.size()>0) {
				return R.failed("媒体为穿山甲时不需要基础创意组件");
			}
		}

		//广告计划-落地页
		if (StringUtils.isNotBlank(adPlan.getDownloadType())
				&& adPlan.getDownloadType().equals("EXTERNAL_URL")) {

			if (StringUtils.isBlank(record.getSource())) {
				return R.failed("落地页广告计划的创意必须指定 来源");
			}

			if (StringUtils.isNotBlank(record.getWebUrl())) {
				return R.failed("落地页广告计划的创意 不能指定详情页");
			}

//			if (StringUtils.isNotBlank(record.getAppName()))
//				return R.failed("落地页广告计划的创意 不能指定应用名");

			if (StringUtils.isNotBlank(record.getSubTitle())) {
				return R.failed("落地页广告计划的创意 不能指定副标题");
			}
			//新营销链路创意DownloadType = EXTERNAL_URL需要 落地页字段
			record.setExternalUrl(adPlan.getExternalUrl());

		} else {
			//非落地页
			if (StringUtils.isNotBlank(record.getSource())) {
				return R.failed("非法的字段 来源source");
			}
			if (StringUtils.isBlank(record.getWebUrl())) {
				return R.failed("未提供详情页");

				//v2.4.3 前端去除应用名称的输入，改为取对应联调转化的应用名
//			if (StringUtils.isBlank(record.getAppName()))
//				return R.failed("未提供应用名");
			}
			record.setExternalUrl("");
		}

		//创意方式:程序化创意
		if (StringUtils.isNotBlank(record.getCreativeMaterialMode())
				&& record.getCreativeMaterialMode().equals("STATIC_ASSEMBLE")) {
			if (record.getGenerateDerivedAd() == null) {
				return R.failed("程序化创意需要提供 最优创意衍生计划 选项");
			}
			if (record.getIsPresentedVideo() == null) {
				return R.failed("程序化创意需要提供 自动生成视频素材 选项");
			}
			JSONObject creativeObj = JSON.parseObject(record.getCreatives());
			JSONArray arr = creativeObj.getJSONArray("title_materials");
			if (arr !=null || arr.size()>0){
				for (int i = 0; i < arr.size(); i++) {
					JSONObject obj = arr.getJSONObject(i);
					String title = obj.getString("title");
					if (!title.contains("{")){
						//没有词包，则不传word_list
						obj.remove("word_list");
					}
					int titleLen = titleLength(title);
					if (titleLen < 5 || titleLen > 30) {
						return R.failed("创意标题 长度为5-30个字（注：2个英文字符算一个字）");
					}
				}
				//重新设置
				creativeObj.put("title_materials",arr);
				record.setCreatives(JSON.toJSONString(creativeObj));
			}
		}

		//创意方式:自定义创意
		if (StringUtils.isBlank(record.getCreativeMaterialMode())) {
			if (record.getGenerateDerivedAd() != null) {
				return R.failed("自定义创意不提供 最优创意衍生计划 选项");
			}

			if (record.getIsPresentedVideo() != null) {
				return R.failed("自定义创意不提供 自动生成视频素材 选项");
			}

			// 是否将视频的封面和标题同步到图片创意 校验
			if (InventoryCatalogEnum.MANUAL.getValue().equals(record.getInventoryCatalog())) {
				//媒体类型包含抖音,创意组件必填
				List<Integer> derives = getDerivePosterCid(record);
				if (record.getInventoryType().contains("INVENTORY_AWEME_FEED")
					&& !CollectionUtils.isEmpty(derives)) {
					return R.failed("首选媒体包含抖音时，不能勾选同步功能");
				}
			}

			//创意标题校验
			if (StringUtils.isNotBlank(record.getCreatives())) {
				JSONArray arr = JSON.parseArray(record.getCreatives());
				if (arr !=null || arr.size()>0){
					for (int i = 0; i < arr.size(); i++) {
						JSONObject obj = arr.getJSONObject(i);
						JSONObject titleObj = obj.getJSONObject("title_material");
						String title = titleObj.getString("title");
						if (!title.contains("{")){
							//没有词包，则不传word_list
							titleObj.remove("word_list");
						}
//						else {
//							JSONArray word_list = new JSONArray();
//							JSONArray wordArr = titleObj.getJSONArray("word_list");
//							for (int j=0;j<wordArr.size();j++) {
//								JSONObject wordIdObj = new JSONObject();
//								String wordId = wordArr.getJSONObject(j).getString("word_id");
//								wordIdObj.put("word_id",Integer.parseInt(wordId));
//								word_list.add(wordIdObj);
//							}
//							titleObj.put("word_list",word_list);
//						}
						int titleLen = titleLength(title);
						if (titleLen < 5 || titleLen > 30) {
							return R.failed("创意标题 长度为5-30个字（注：2个英文字符算一个字）");
						}
						//重新设置
						obj.put("title_material",titleObj);
					}
					record.setCreatives(JSON.toJSONString(arr));
				}
			}
		}

		//创意-按场景指定位置
		//v2.4.2新营销链路不需要ActionText，暂时保留
		if (StringUtils.isNotBlank(record.getSceneInventory())) {
			if (record.getSceneInventory().equals("FEED_SCENE")
					&& StringUtils.isBlank(record.getActionText())) {
				return R.failed("信息流场景的创意，行动号召为必选");
			}

			if (record.getSceneInventory().equals("TAIL_SCENE")
					&& StringUtils.isBlank(record.getActionText())) {
				return R.failed("频后贴和尾帧场景的创意，行动号召为必选");
			}
		}


//		if (StringUtils.isNotBlank(record.getAppName())) {
//			int appLen = titleLength(record.getAppName());
//			if (appLen < 2 || appLen > 10)
//				return R.failed("应用名长度应在4到20个字符(英文算一个字符，中文算两个字符)");
//		}

		if (StringUtils.isNotBlank(record.getSubTitle())) {
			int titleLen = titleLength(record.getSubTitle());
			if (titleLen < 2 || titleLen > 12) {
				return R.failed("APP副标题长度应在4到24个字符(英文算一个字符，中文算两个字符)");
			}
		}

		return R.ok("校验成功");
	}

	private static int titleLength(String text) {
		String pattern = "\\{.*?\\}";

		String normalStr = text.replaceAll(pattern, "");
		int cwc = chineseWordCount(normalStr);
		int length = (normalStr.length() + cwc) / 2;

		int gct = 0;
		if (text.contains("{")) {
			for (int i = 0; i < text.length(); i++) {
				if (text.charAt(i) == '{')
					gct++;
			}
		}

		length += gct * 2;
		return length;
	}

	//汉字个数
	public static int chineseWordCount(String text) {
		String Reg = "^[\u4e00-\u9fa5]{1}$";  //正则
		int result = 0;
		for (int i = 0; i < text.length(); i++) {
			String b = Character.toString(text.charAt(i));
			if (b.matches(Reg)) result++;
		}
		return result;
	}

	/**
	 * 自定义创意-获取所有的是否将视频的封面和标题同步到图片创意 字段
	 * 创意组件不能勾选同步checkbox
	 * @param record
	 * @return
	 */
	private  List<Integer> getDerivePosterCid(TtAdCreativeTemp record){
		List<Integer> result = Lists.newArrayList();
		if (StringUtils.isBlank(record.getCreativeMaterialMode())){
			JSONArray cts = JSON.parseArray(record.getCreatives());
			if (cts !=null || cts.size()>0){
				for (int i = 0; i < cts.size(); i++) {
					JSONObject item = cts.getJSONObject(i);
					Integer derive = item.getInteger("derive_poster_cid");
					if (derive != null && derive.intValue() == 1) {
						result.add(derive);
						break;
					}
				}
			}
		}
		return result;
	}

	public static void main(String[] args) {
		//String str = "[{\"component_materials\":[{\"component_id\":\"7007721818064683038\"}],\"video_material\":{\"image_info\":{\"image_id\":\"web.business.image/202101125d0d34da417d349c48f291e1\"},\"video_info\":{\"name\":\"竖版_竖版\",\"video_id\":\"v02033ad0000bumcn280kv8f2mbqhk0g\"}},\"derive_poster_cid\":1,\"title_material\":{\"word_list\":[{\"word_id\":4},{\"word_id\":1736}],\"title\":\"{地点}{星期}xw1测试\"},\"image_mode\":\"CREATIVE_IMAGE_MODE_VIDEO_VERTICAL\",\"sub_title_material\":{\"sub_title\":\"侧是是是\"}},{\"component_materials\":[{\"component_id\":\"7007693771705942055\"}],\"video_material\":{\"image_info\":{\"image_id\":\"web.business.image/202102015d0d5cc6fb74a944410d8cdb\"},\"video_info\":{\"name\":\"横屏1_横版\",\"video_id\":\"v030337d0000c0774ussosforu7ck180\"}},\"derive_poster_cid\":0,\"title_material\":{\"word_list\":[{\"word_id\":4},{\"word_id\":1736}],\"title\":\"{地点}{星期}xw1测试\"},\"image_mode\":\"CREATIVE_IMAGE_MODE_VIDEO\",\"sub_title_material\":{\"sub_title\":\"侧是是是\"}}]";
		String str = "[{\"image_mode\":\"CREATIVE_IMAGE_MODE_VIDEO_VERTICAL\",\"title_material\":{\"title\":\"通用测试的项xw1\"},\"video_material\":{\"image_info\":{\"image_id\":\"web.business.image/202101125d0d34da417d349c48f291e1\"},\"video_info\":{\"video_id\":\"v02033ad0000bumcn280kv8f2mbqhk0g\",\"name\":\"竖版_竖版\"}},\"name\":\"竖版_竖版\",\"derive_poster_cid\":0,\"sub_title_material\":{\"sub_title\":\"\"},\"component_materials\":[{\"component_id\":\"7007675103915802663\"}]},{\"image_mode\":\"CREATIVE_IMAGE_MODE_VIDEO\",\"title_material\":{\"title\":\"{地点}{星期}xw1测试\",\"word_list\":[{\"word_id\":4},{\"word_id\":1736}]},\"video_material\":{\"image_info\":{\"image_id\":\"web.business.image/202102015d0d5cc6fb74a944410d8cdb\"},\"video_info\":{\"video_id\":\"v030337d0000c0774ussosforu7ck180\",\"name\":\"横屏1_横版\"}},\"name\":\"横屏1_横版\",\"derive_poster_cid\":0,\"sub_title_material\":{\"sub_title\":\"\"},\"component_materials\":[{\"component_id\":\"7007675103915802663\"}]},{\"image_mode\":\"CREATIVE_IMAGE_MODE_LARGE\",\"title_material\":{\"title\":\"0722的文案\"},\"image_materials\":[{\"image_info\":{\"image_id\":\"337b6000dc99b3a7c956c\",\"name\":\"横版大图2_横图\"}}],\"name\":\"横版大图2_横图\",\"sub_title_material\":{\"sub_title\":\"\"}}]";
		JSONArray jsonArray = JSON.parseArray(str);
		TtAdCreativeTemp record = new TtAdCreativeTemp();
		record.setInventoryType("INVENTORY_FEED,INVENTORY_VIDEO_FEED,INVENTORY_HOTSOON_FEED,INVENTORY_UNION_SLOT,INVENTORY_AWEME_FEED");
		record.setCreatives(str);
//		System.out.println(getDerivePosterCid(record));
//		List<Integer> derives = getDerivePosterCid(record);

//		if (record.getInventoryType().contains("INVENTORY_AWEME_FEED")
//				&& !CollectionUtils.isEmpty(derives)) {
//			System.out.println("首选媒体包含抖音时，不能勾选同步功能");
//		}
		Integer a = 1;
		System.out.println(a==1);
		System.out.println(a.intValue()==1);
	}

	/**
	 * 当值为"STATIC_ASSEMBLE"表示程序化创意
	 * @param record
	 * @return
	 */
	private List<String> getImagesMode(TtAdCreativeTemp record) {
		List<String> rst = new ArrayList<>();
		if (StringUtils.isNotBlank(record.getCreativeMaterialMode())
				&& record.getCreativeMaterialMode().equals("STATIC_ASSEMBLE")) {
			JSONObject creativeObj = JSON.parseObject(record.getCreatives());
			JSONArray imageList = creativeObj.getJSONArray("image_materials");
			JSONArray videoList = creativeObj.getJSONArray("video_materials");
			if (imageList !=null || imageList.size()>0){
				for (int i = 0; i < imageList.size(); i++) {
					JSONObject item = imageList.getJSONObject(i);
					rst.add(item.getString("image_mode"));
				}
			}
			if (videoList !=null || videoList.size()>0){
				for (int i = 0; i < videoList.size(); i++) {
					JSONObject item = videoList.getJSONObject(i);
					rst.add(item.getString("image_mode"));
				}
			}
		} else {
			JSONArray cts = JSON.parseArray(record.getCreatives());
			if (cts !=null || cts.size()>0){
				for (int i = 0; i < cts.size(); i++) {
					JSONObject item = cts.getJSONObject(i);
					rst.add(item.getString("image_mode"));
				}
			}
		}
		return rst.stream().distinct().collect(Collectors.toList());
	}

	/**
	 * 获取创意组件
	 * 媒体必须包含抖音才能选择创意组件
	 * @param record
	 * @return
	 */
	private JSONArray getComponentMaterials(TtAdCreativeTemp record){
		JSONArray result = new JSONArray();
		//程序化
		if (StringUtils.isNotBlank(record.getCreativeMaterialMode())) {
			JSONObject creativeObj = JSON.parseObject(record.getCreatives());
			return creativeObj.getJSONArray("component_materials");
		} else {
			JSONArray cts = JSON.parseArray(record.getCreatives());
			if (cts !=null || cts.size()>0){
				for (int i = 0; i < cts.size(); i++) {
					JSONObject item = cts.getJSONObject(i);
					JSONArray componentMaterials = item.getJSONArray("component_materials");
					if (componentMaterials != null && componentMaterials.size()>0) {
						result.add(item.getJSONArray("component_materials"));
					}
				}
			}
			return result;
		}
	}

	@Override
	public R detailById(Long id) {
		if (null == id) {
			return R.failed("未获取到主键id");
		}
		TtAdCreativeTemp record = ttAdCreativeTempMapper.selectById(id);
		return R.ok(record);
	}




}
